import QtQuick 2.0
import QtGraphicalEffects 1.12
import QtQuick.Controls 2.12
import QtQuick.Layouts 1.12
import "../components"
Item {
    id: root
    readonly property real dp: config.dp

    // 方法 ==================================================================================



    property int row: 8
    property int col: 12
    property int gridSize: Math.min((root.height-20*dp) / row, (root.width-20*dp) / col)

    property int maskX: 0
    property int maskY: 0
    property int maskX2: 0
    property int maskY2: 0

    property var selectedList: []
    property bool keepSelect: false     // ctrl按下时，若第一个是未选中状态，则持续选中
    property bool keepUnselect: false   // 若第一个是已选中状态，则持续取消

    property var pasteValue: ({
                                   "SampleName": "",
                                   "SampleType": "",
                                   "SampleConc": "",
                                   "FAM": "",
                                   "VIC": "",
                                   "ROX": "",
                                   "CY5": ""
                               })

    onVisibleChanged: {
        for(let r = 0; r < row; r ++){
            for(let c = 0; c < col; c ++){
                repeater.itemAt(r*col + c).setUnselect()
            }
        }
        selectedList = []
        root.selectedChanged()
        pannelMenu.visible = false
    }

    function getSelectedList(){
        // 返回选中列表
        return selectedList
    }

    // 展示
    function setSampleList(slist){

        let nn = 0, ss = 0, uu = 0, aa = 0
        for(let c = 0; c < col; c ++){
            for(let r = 0; r < row; r ++){
                let idx = r*col + c
                if(idx >= slist.length){
                    continue
                }
                if(slist[idx]["SampleType"]==="标准"){
                    ss ++
                }else if(slist[idx]["SampleType"]==="阴性"){
                    nn ++
                }else if(slist[idx]["SampleType"]==="未知"){
                    uu ++
                }
                if(slist[idx]["SampleName"] !== "" ||
                   slist[idx]["SampleType"] !== "" ||
                   slist[idx]["FAM"].toString() !== "0" ||
                   slist[idx]["VIC"].toString() !== "0" ||
                   slist[idx]["CY5"].toString() !== "0" ||
                   slist[idx]["ROX"].toString() !== "0")
                    aa ++

                repeater.itemAt(idx).refresh(slist[idx])
            }
        }
        countN = nn
        countS = ss
        countU = uu
        countAll = aa

    }

    signal selectedChanged()



    // 样式 ===================================================================================

    anchors.fill: parent
    Rectangle{  // 左侧序号
        height: gridSize * row
        width: 20*dp
        y: 20*dp
        Column{
            Repeater{
                model: ["A", "B", "C", "D", "E", "F", "G", "H"]
                Item{
                    width: 20*dp
                    height: gridSize
                    Text {
                        text: qsTr(modelData)
                        anchors.centerIn: parent
                    }
                }
            }
        }
    }
    Rectangle{  // 上方序号
        height: 20*dp
        width: gridSize * col
        x: 20*dp
        Row{
            Repeater{
                model: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]
                Item{
                    height: 20*dp
                    width: gridSize
                    Text {
                        text: qsTr(modelData)
                        anchors.centerIn: parent
                    }
                }
            }
        }
    }
    Rectangle{  // 样本板
        id: pannel
        height: gridSize * row
        width: gridSize * col
        x: 20*dp
        y: 20*dp
        Grid{
            columns: col
            rows: row
            columnSpacing: 3*dp
            rowSpacing: 3*dp
            Repeater{
                id: repeater
                model: col * row
                SampleItem{
                    height: gridSize-3*dp
                    width: gridSize-3*dp
                }
            }
        }

        MouseArea{
            anchors.fill: parent
            property bool isPressed: false
            acceptedButtons: Qt.LeftButton | Qt.RightButton
            onClicked: {
                if(mouse.button === Qt.RightButton){        // 右键点击事件
                    if(!isEditable) return
                    // 规则：1. 只能对已选择的区域点击
                    //      2. 已选择区域只有一个元素时，可复制和粘贴
                    //      3. 已选择区域有多个元素时，仅可粘贴
                    var mousePos = mapToItem(pannel, mouseX, mouseY)
                    maskX = mousePos.x
                    maskY = mousePos.y
                    var r = Math.floor(maskY / gridSize)
                    var c = Math.floor(maskX / gridSize)

                    if(selectedList.indexOf(r*col+c) === -1){
                        for(let i = 0; i < row*col; i ++){
                            repeater.itemAt(i).setUnselect()
                        }repeater.itemAt((r*col+c)).setSelect()
                        selectedList = [r*col+c]
                    }

                    if(selectedList.length === 1){
                        pannelMenu.canCopy = true
                    }else{
                        pannelMenu.canCopy = false
                    }
                    pannelMenu.visible = true
                    pannelMenu.x = mousePos.x
                    pannelMenu.y = mousePos.y
                    pannelMenu.curRow = r
                    pannelMenu.curCol = c

                }
            }

            onPressed: {
                if(mouse.button === Qt.RightButton){
                    return
                }
                pannelMenu.visible = false
                isPressed = true
                var mousePos = mapToItem(pannel, mouseX, mouseY)
                maskX = mousePos.x
                maskY = mousePos.y
                maskX = Math.min(pannel.width-1, maskX)
                maskY = Math.min(pannel.height-1, maskY)
                maskX = Math.max(0, maskX)
                maskY = Math.max(0, maskY)

                var r = Math.floor(maskY / gridSize)
                var c = Math.floor(maskX / gridSize)

                if(gKeyPressed_ctrl){
                    if(selectedList.indexOf(r*col+c) === -1){
                        keepSelect = true
                        keepUnselect = false
                    }else{
                        keepUnselect = true
                        keepSelect = false
                    }
                }else{
                    keepSelect = false
                    keepUnselect = false
                }

                if(!(keepSelect||keepUnselect)){
                    for(let i = 0; i < row*col; i ++){
                        repeater.itemAt(i).setUnselect()
                    }
                    selectedList = []
                }
                root.focus = true
                positionChanged(mousePos.x, mousePos.y)       // （触发一下PositionChanged的效果
            }
            onPositionChanged: {
                if(!isPressed) return
                var mousePos = mapToItem(pannel, mouseX, mouseY)
                maskX2 = mousePos.x
                maskY2 = mousePos.y
                maskX2 = Math.min(pannel.width-1, maskX2)
                maskY2 = Math.min(pannel.height-1, maskY2)
                maskX2 = Math.max(0, maskX2)
                maskY2 = Math.max(0, maskY2)
                // 计算开始和结束的行列
                var row1 = Math.min(Math.floor(maskY / gridSize), Math.floor(maskY2 / gridSize))
                var row2 = Math.max(Math.floor(maskY / gridSize), Math.floor(maskY2 / gridSize))
                var col1 = Math.min(Math.floor(maskX / gridSize), Math.floor(maskX2 / gridSize))
                var col2 = Math.max(Math.floor(maskX / gridSize), Math.floor(maskX2 / gridSize))


                for(let i = 0; i < row*col; i ++){
                    repeater.itemAt(i).setUnselect()
                }
                for(let i = 0; i < selectedList.length; i ++){
                    repeater.itemAt(selectedList[i]).setSelect()
                }

                for(let r = row1; r <= row2; r ++){
                    for(let c = col1; c <= col2; c ++){
                        if(keepUnselect){
                            repeater.itemAt(r*col + c).setUnselect()
                        }else{
                            repeater.itemAt(r*col + c).setSelect()
                        }
                    }
                }

            }
            onReleased: {

                if(mouse.button === Qt.RightButton){
                    return
                }
                isPressed = false
                var mousePos = mapToItem(pannel, mouseX, mouseY)
                maskX2 = mousePos.x
                maskY2 = mousePos.y
                maskX2 = Math.min(pannel.width-1, maskX2)
                maskY2 = Math.min(pannel.height-1, maskY2)
                maskX2 = Math.max(0, maskX2)
                maskY2 = Math.max(0, maskY2)
//                mask.visible = false

                // 计算开始和结束的行列
                var row1 = Math.min(Math.floor(maskY / gridSize), Math.floor(maskY2 / gridSize))
                var row2 = Math.max(Math.floor(maskY / gridSize), Math.floor(maskY2 / gridSize))
                var col1 = Math.min(Math.floor(maskX / gridSize), Math.floor(maskX2 / gridSize))
                var col2 = Math.max(Math.floor(maskX / gridSize), Math.floor(maskX2 / gridSize))

                for(let r = row1; r <= row2; r ++){
                    for(let c = col1; c <= col2; c ++){
                        if(keepUnselect){
                            repeater.itemAt(r*col + c).setUnselect()
                            if(selectedList.indexOf(r*col+c)!==-1){
                                selectedList.splice(selectedList.indexOf(r*col+c), 1)
                            }
                        }else{
                            repeater.itemAt(r*col + c).setSelect()
                            if(selectedList.indexOf(r*col+c)===-1){
                                selectedList.push(r*col+c)
                            }
                        }
                    }
                }
                root.selectedChanged()
            }
        }
        Rectangle{      // 右键菜单
            id: pannelMenu
            height: 60*dp
            width: 60*dp
            visible: false
            property int curCol: 0
            property int curRow: 0
            property bool canCopy: false
            property bool canPaste: false

            border.color: Qt.rgba(0, 0, 0, 0.01)
            border.width: 12*dp

            layer.enabled: true
            layer.effect: DropShadow{
                color: "#BBBBBB"
                samples: 32
                radius: 12*dp
                spread: 0.1
            }
            Rectangle{
                anchors.fill: parent
                radius: 3
            }
            PushButton{
                title: "复制"
                height: 30*dp; width: 60*dp
                button_color_hover: config.color_blue0
                button_border_disable: "transparent"
                button_color_disable: "white"
                isDisabled: !pannelMenu.canCopy
                onReleased: {
                    pannelMenu.visible = false
                    pasteValue = sampleList[pannelMenu.curRow*col + pannelMenu.curCol]
                    pannelMenu.canPaste = true
                }
            }PushButton{
                title: "粘贴"
                height: 30*dp; width: 60*dp; y: 30*dp
                button_color_hover: config.color_blue0
                button_border_disable: "transparent"
                button_color_disable: "white"
                isDisabled: !pannelMenu.canPaste
                onReleased: {
                    pannelMenu.visible = false
                    for(let i = 0; i < selectedList.length; i ++){
                        sampleList[selectedList[i]]["SampleName"] = pasteValue["SampleName"]
                        sampleList[selectedList[i]]["SampleType"] = pasteValue["SampleType"]
                        sampleList[selectedList[i]]["SampleConc"] = pasteValue["SampleConc"]
                        sampleList[selectedList[i]]["FAM"] = pasteValue["FAM"]
                        sampleList[selectedList[i]]["VIC"] = pasteValue["VIC"]
                        sampleList[selectedList[i]]["ROX"] = pasteValue["ROX"]
                        sampleList[selectedList[i]]["CY5"] = pasteValue["CY5"]
                    }
                    sampleChanged()
                    setSampleList(sampleList)
                }
            }
        }
        Rectangle{
            id: mask
            color: Qt.rgba(0.8,0.8,1,0.1)
            border.color: Qt.rgba(0.8,0.8,1,0.6)
            border.width: 2*dp
        }
    }
}
